package cn.xxm.scene.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: scene-rule
 * @link: 55864455@qq.com
 * @author: Mr.Xxm
 * @create: 2020-02-22 19:56
 **/
public class WebHelper {


    /**
     * 获取HttpServletRequest
     * @return
     */
    public static HttpServletRequest getHttpServletRequest(){
        HttpServletRequest request = null;
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(null != attributes){
            request  = attributes.getRequest();
        }
        return request;
    }

    /**
     * 获取HttpServletResponse
     * @return
     */
    public static HttpServletResponse getHttpServletResponse(){
        HttpServletResponse response = null;
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(null != attributes){
            response  = attributes.getResponse();
        }
        return response;
    }


    /**
     * 获取Request域中的数据
     * @param key
     * @return
     */
    public static Object getRequestAttribute(String key){
        Object value = null;
        HttpServletRequest request = getHttpServletRequest();
        if(null != request){
            value =   request.getAttribute(key);
        }
        return value;
    }


    /**
     * 向Request域中压入数据
     * @param key
     * @return
     */
    public static void setRequestAttribute(String key,Object value){
        HttpServletRequest request = getHttpServletRequest();
        if(null != request){
           request.setAttribute(key,value);
        }
    }

}
